#include<stdio.h>
#include<stdlib.h>

typedef struct ListNode {
	int val;
	struct ListNode *next;
}SLTNode;

struct ListNode* removeElements(struct ListNode* head, int val){
	SLTNode* cur = head;
	if (cur == NULL)
	{
		return head;
	}

	while (cur->next != NULL)
	{
		if (cur->next->val == val)
		{
			SLTNode* temp2 = cur->next;
			if (cur->next->next == NULL)
			{
				SLTNode* temp3 = cur->next;
				cur->next = cur->next->next;
				free(temp3);
				if (cur->val == val)
				{
					SLTNode* temp1 = head;
					head = cur->next;
					cur = head;
					free(temp1);
				}
				break;
			}
			cur->next = cur->next->next;
			temp2->next = NULL;
			free(temp2);
		}
		else
		{
			cur = cur->next;
		}
	}
	cur = head;
	if (cur != NULL)
	{
		if (cur->val == val)
		{
			SLTNode* temp1 = head;
			head = cur->next;
			cur = head;
			free(temp1);
		}
	}

	return head;

}
SLTNode* BuySLTNode(int x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->val = x;
	newnode->next = NULL;
	return newnode;
};
void SLTPrint(SLTNode* head)
{
	SLTNode* cur = head;
	while (cur != NULL)
	{
		printf("%d->", cur->val);
		cur = cur->next;
	}
	printf("NULL\n");
}
int main()
{
	SLTNode* n1 = BuySLTNode(1);
	SLTNode* n2 = BuySLTNode(2);
	/*SLTNode* n3 = BuySLTNode(6);
	SLTNode* n4 = BuySLTNode(6);
	SLTNode* n5 = BuySLTNode(6);
	SLTNode* n6 = BuySLTNode(6);
	SLTNode* n7 = BuySLTNode(6);*/
	n1->next = n2;
	n2->next = NULL;
	/*n2->next = n3;
	n3->next = n4;
	n4->next = n5;
	n5->next = n6;
	n6->next = n7;
	n7->next = NULL;*/
	SLTPrint(n1);
	struct ListNode* s = removeElements(n1, 1);
	SLTPrint(s);
	system("pause");
	return 0;
}